//
//  Copyright 2015 XiaoJSoft Studio.
//  Copyright 2015 Harbin Institute of Technology(HIT), Software Engineering Department.
//
//  Use of this source code is governed by a proprietary license. You can not read, change or
//  redistribute this source code unless you have a written authorization from the copyright
//  holder listed above.
//

#include "text_file.h"
#include "codec.h"
#include <QFile>
#include <QString>
#include <QIODevice>
#include <QTextStream>
#include <string>

namespace ui {
namespace compiler {

bool textFileWrite(const std::string &file_path, const std::string &content) {
    //  Open the file.
    QFile file_handler(QString::fromStdString(file_path));
    if (!file_handler.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) {
        return false;
    }

    //  Write the content.
    QTextStream stream(&file_handler);
    stream.setCodec(UIJS_COMPILER_TEXT_CODEC);
    stream << QString::fromStdString(content);
    stream.flush();

    //  Close the file.
    file_handler.close();

    return true;
}

bool textFileRead(const std::string &file_path, std::string &output) {
    //  Open the file.
    QFile file_handler(QString::fromStdString(file_path));
    if (!file_handler.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }

    //  Read the content.
    QTextStream stream(&file_handler);
    stream.setCodec(UIJS_COMPILER_TEXT_CODEC);
    output = stream.readAll().toStdString();

    //  Close the file.
    file_handler.close();

    return true;
}

}  //  namespace compiler
}  //  namespace ui
